package com.gemme.gemme.wode;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.MyOSSUtils;
import com.gemme.gemme.util.QRCodeUtil;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.webview.BrowserActivity;
import com.gemme.gemme.webview.SonicJavaScriptInterface;
import com.jaeger.library.StatusBarUtil;
import com.just.agentweb.AgentWeb;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//侧滑删除地址
public class FuZhiJIanCeActivity extends BaseActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fzjc);
        initTop();
//        initData();
//        testOss();
//        testOssVideo();
//        initWebView();
//        initAgent();
        requestPermission();
        initSonic();
    }

    private void initSonic() {
        findViewById(R.id.bt_sonic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, BrowserActivity.class);
                intent.putExtra(BrowserActivity.PARAM_URL, "https://api.skinrun.cn/html/ai/index.html?token=qpIT382W2TpJopgqmi9Ejmhc3fchCjWwi%2F31kAdmNTQqzAhw2URgdw");
                intent.putExtra(BrowserActivity.PARAM_MODE, BrowserActivity.MODE_SONIC);
                intent.putExtra(SonicJavaScriptInterface.PARAM_CLICK_TIME, System.currentTimeMillis());
                startActivityForResult(intent, -1);
            }
        });
    }

    private void initAgent() {
        LinearLayout view = findViewById(R.id.ll);
        AgentWeb mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) view, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("https://api.skinrun.cn/html/ai/index.html?token=qpIT382W2TpJopgqmi9Ejmhc3fchCjWwi%2F31kAdmNTQqzAhw2URgdw")
//                .go("http://www.jd.com")
                ;
//        mAgentWeb.getJsEntraceAccess().quickCallJs("callByAndroid");
        mAgentWeb.getJsAccessEntrace().quickCallJs("callByAndroid");
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterface(mAgentWeb,this));
//        window.android.callAndroid();
    }

    /**
     * 申请权限
     */
    public static final int CAMERA_REQ_CODE = 111;
    private void requestPermission() {
        // 判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            // 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
//                showAlert("请进入设置-应用管理-打开相机权限");
            } else {
                // 进行权限请求
                ActivityCompat
                        .requestPermissions(
                                this,
                                new String[]{Manifest.permission.CAMERA},
                                CAMERA_REQ_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQ_CODE: {
                // 如果请求被拒绝，那么通常grantResults数组为空
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 申请成功，进行相应操作
                } else {
                    // 申请失败，可以继续向用户解释。
//                    showAlert("没有相机权限,您可能无法使用相机");
                }
                return;
            }
        }
    }


/*
    private void initWebView() {
        //获得控件
        WebView webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();

        // step 4: bind javascript
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");

        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
    //访问网页
    webView.loadUrl("https://api.skinrun.cn/html/ai/index.html?token=qpIT382W2TpJopgqmi9Ejmhc3fchCjWwi%2F31kAdmNTQqzAhw2URgdw");
    //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        webView.setWebViewClient(new WebViewClient(){
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    //使用WebView加载显示url
                    view.loadUrl(url);
                    //返回true
                    return true;
                }
        });


        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
               */
/* if (newProgress == 100) {
                    bar.setVisibility(View.INVISIBLE);
                    // line.setVisibility(View.VISIBLE);
                } else {
                    if (View.INVISIBLE == bar.getVisibility()) {
                        bar.setVisibility(View.VISIBLE);
                    }
                    bar.setVisibility(View.INVISIBLE);
                    bar.setProgress(newProgress);
                    bar.setVisibility(View.VISIBLE);
                }*//*

                super.onProgressChanged(view, newProgress);
            }

            */
/**
             * 8(Android 2.2) <= API <= 10(Android 2.3)回调此方法
             *//*

            private void openFileChooser(android.webkit.ValueCallback<Uri> uploadMsg) {
                Log.e("WangJ", "运行方法 openFileChooser-1");
                // (2)该方法回调时说明版本API < 21，此时将结果赋值给 mUploadCallbackBelow，使之 != null
                mUploadCallbackBelow = uploadMsg;
                takePhoto();
            }

            */
/**
             * 11(Android 3.0) <= API <= 15(Android 4.0.3)回调此方法
             *//*

            public void openFileChooser(android.webkit.ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.e("WangJ", "运行方法 openFileChooser-2 (acceptType: " + acceptType + ")");
                // 这里我们就不区分input的参数了，直接用拍照
                openFileChooser(uploadMsg);
            }

            */
/**
             * 16(Android 4.1.2) <= API <= 20(Android 4.4W.2)回调此方法
             *//*

            public void openFileChooser(android.webkit.ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.e("WangJ", "运行方法 openFileChooser-3 (acceptType: " + acceptType + "; capture: " + capture + ")");
                // 这里我们就不区分input的参数了，直接用拍照
                openFileChooser(uploadMsg);
            }

            */
/**
             * API >= 21(Android 5.0.1)回调此方法
             *//*

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                Log.e("WangJ", "运行方法 onShowFileChooser");
                // (1)该方法回调时说明版本API >= 21，此时将结果赋值给 mUploadCallbackAboveL，使之 != null
                mUploadCallbackAboveL = valueCallback;
                takePhoto();
                return true;
            }

        });


    }
*/


    /**
     * 调用相机
     */
    Uri  imageUri;

    private void takePhoto() {
        // 指定拍照存储位置的方式调起相机
        String filePath = Environment.getExternalStorageDirectory() + File.separator
                + Environment.DIRECTORY_PICTURES + File.separator;
        String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        imageUri = Uri.fromFile(new File(filePath + fileName));

        //        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //        startActivityForResult(intent, REQUEST_CODE);


        // 选择图片（不包括相机拍照）,则不用成功后发刷新图库的广播
        //        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        //        i.addCategory(Intent.CATEGORY_OPENABLE);
        //        i.setType("image/*");
        //        startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE);

        Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        Intent Photo = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        Intent chooserIntent = Intent.createChooser(Photo, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});

        startActivityForResult(chooserIntent, 99);
    }


    /**
     * Android API < 21(Android 5.0)版本的回调处理
     * @param resultCode
     *         选取文件或拍照的返回码
     * @param data
     *         选取文件或拍照的返回结果
     */
    private void chooseBelow(int resultCode, Intent data) {
        Log.e("WangJ", "返回调用方法--chooseBelow");

        if (RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对文件路径处理
                Uri uri = data.getData();
                if (uri != null) {
                    Log.e("WangJ", "系统返回URI：" + uri.toString());
                    mUploadCallbackBelow.onReceiveValue(uri);
                } else {
                    mUploadCallbackBelow.onReceiveValue(null);
                }
            } else {
                // 以指定图像存储路径的方式调起相机，成功后返回data为空
                Log.e("WangJ", "自定义结果：" + imageUri.toString());
                mUploadCallbackBelow.onReceiveValue(imageUri);
            }
        } else {
            mUploadCallbackBelow.onReceiveValue(null);
        }
        mUploadCallbackBelow = null;
    }

    /**
     * Android API >= 21(Android 5.0) 版本的回调处理
     * @param resultCode
     *         选取文件或拍照的返回码
     * @param data
     *         选取文件或拍照的返回结果
     */
    private void chooseAbove(int resultCode, Intent data) {
        Log.e("WangJ", "返回调用方法--chooseAbove");

        if (RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对从文件中选图片的处理
                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
                    results = new Uri[]{uriData};
                    for (Uri uri : results) {
                        Log.e("WangJ", "系统返回URI：" + uri.toString());
                    }
                    mUploadCallbackAboveL.onReceiveValue(results);
                } else {
                    mUploadCallbackAboveL.onReceiveValue(null);
                }
            } else {
                Log.e("WangJ", "自定义结果：" + imageUri.toString());
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{imageUri});
            }
        } else {
            mUploadCallbackAboveL.onReceiveValue(null);
        }
        mUploadCallbackAboveL = null;
    }

    private android.webkit.ValueCallback<Uri[]> mUploadCallbackAboveL;
    private android.webkit.ValueCallback<Uri>   mUploadCallbackBelow;

    private void updatePhotos() {
        // 该广播即使多发（即选取照片成功时也发送）也没有关系，只是唤醒系统刷新媒体文件
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(imageUri);
        sendBroadcast(intent);
    }


    private void testOssVideo() {
        try {
            long l = System.currentTimeMillis();
            String videopath = "/storage/emulated/0/Movies/VID_20200716_11564190.mp4";
            String videoName =  new File(videopath).getName().replace(".",l+".");
            MyOSSUtils.getInstance().upVideo(this, new MyOSSUtils.OssUpCallback() {
                @Override
                public void successImg(String img_url) {
                    System.out.println("");
                }

                @Override
                public void successVideo(String video_url) {
                    System.out.println("");
                }

                @Override
                public void inProgress(long progress, long zong) {
                    System.out.println("");
                }
            }, videoName, videopath);
        }catch (Exception e){

        }


    }

    private void testOss() {
        long l = System.currentTimeMillis();
        String mPicturePath = "/storage/emulated/0/DCIM/Camera/IMG_20200721_083411.jpg";
        String objectName =  new File(mPicturePath).getName().replace(".",l+".");
        MyOSSUtils.getInstance().upImage(this, new MyOSSUtils.OssUpCallback() {
        @Override
        public void successImg(String img_url) {
            System.out.println("");
        }

        @Override
        public void successVideo(String video_url) {
            System.out.println("");
        }

        @Override
        public void inProgress(long progress, long zong) {
            System.out.println("");
        }
    }, objectName, mPicturePath);
    }

    String Api_Key;
    String Version;
    private void initData() {
        SharedPreferences MSP = getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
        String access_token = MSP.getString(Constant.ACCESS_TOKEN, "").trim();
        if(TextUtils.isEmpty(access_token))
            return;
        String url = DataManager.BaseUrl + "user/thirdaccount/jfgj?type=JFGJ";
        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put(DataManager.AuthorizationKey,"Bearer " + access_token);

        DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headHashMap, new DataManager.GeResponse(){

            @Override
            public void onResponse(String response) {
                try {
                    System.out.println("");

                    Api_Key = ((new JSONObject(response)).getJSONObject("data")).getString("Api_Key");

                    Version = ((new JSONObject(response)).getJSONObject("data")).getString("Version");
                    getPicture();

                }catch (Exception e){

                }

            }
        });
    }

    private void getPicture() {
     /*   try {
            long l = System.currentTimeMillis();
            String mPicturePath = "/storage/emulated/0/Tencent/QQ_Images/null6ffd85a864063dbc.jpg";
            String objectName =  new File(mPicturePath).getName().replace(".",l+".");
//                    mService.asyncPutImage(objectName, mPicturePath);
        MyOSSUtils.getInstance().upImage(this, new MyOSSUtils.OssUpCallback() {
            @Override
            public void successImg(String img_url) {
                System.out.println("");
                if(!TextUtils.isEmpty(img_url))
                getJIfuData(Api_Key,Version,img_url);
            }

            @Override
            public void successVideo(String video_url) {
                System.out.println("");
            }

            @Override
            public void inProgress(long progress, long zong) {
                System.out.println("");
            }
        }, objectName, mPicturePath);


    }catch (Exception e){

    }*/

//        getJIfuData(Api_Key,Version,"http://gemme.oss-cn-hangzhou.aliyuncs.com/gemmeApp/2020-07-20/photo/null6ffd85a864063dbc1595238459848.jpg");
}

    private void getJIfuData(String api_key, String version,String imageUrl) {
        if(TextUtils.isEmpty(api_key) || TextUtils.isEmpty(version))
            return;
        String url = "https://api.skinrun.cn/face?";
        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put("token",api_key);
        headHashMap.put("version",version);
/*        File file = new File("/storage/emulated/0/Tencent/QQ_Images/null6ffd85a864063dbc.jpg");
        if(!file.exists())
            return*/;
        Fzjc fzjc = new Fzjc();
        fzjc.setImage(imageUrl);
        fzjc.setAge("23");
        String json = JSON.toJSONString(fzjc);

        DataManager.toServer2(mContext, url, DataManager.POST_TYPE, json, headHashMap, new DataManager.GeResponse(){

            @Override
            public void onResponse(String response) {
                try {
                    System.out.println("");

                }catch (Exception e){

                }

            }
        });





    }


    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("肤质检测");
    }


    class Fzjc{
        String image;

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        String age;


    }


}